//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.hecai.scanning.util;

import com.hecai.scanning.config.ConfigProperties;
import com.hecai.scanning.handler.ScannerHandler;
import gnu.io.CommPortIdentifier;
import lombok.extern.slf4j.Slf4j;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.service.IoConnector;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.transport.serial.SerialAddress;
import org.apache.mina.transport.serial.SerialAddress.DataBits;
import org.apache.mina.transport.serial.SerialAddress.FlowControl;
import org.apache.mina.transport.serial.SerialAddress.Parity;
import org.apache.mina.transport.serial.SerialAddress.StopBits;
import org.apache.mina.transport.serial.SerialConnector;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Component
public class GreenJadorScanner implements Runnable
{
    private static final int BOARDRATE = 9600;

    private Map<String, IoSession> commSessionMap = new ConcurrentHashMap();

    private List<String> commList = new ArrayList();

    @Autowired
    private ConfigProperties properties;

    public void run()
    {
        try
        {
            while (true)
            {
                Thread.sleep(3000L);
                this.scanComms();
            }
        } catch (InterruptedException var2)
        {
            log.error("Scanner comm has a error.{}", var2);
        }
    }

    private void createIoSession(String commName) throws InterruptedException
    {
        IoConnector connector = new SerialConnector();
        connector.getFilterChain().addLast("logger", new LoggingFilter());
        connector.setHandler(new ScannerHandler());
        SerialAddress address = new SerialAddress(commName, 9600, DataBits.DATABITS_8, StopBits.BITS_1, Parity.NONE,
                FlowControl.NONE);
        ConnectFuture future = connector.connect(address);
        future.await();
        IoSession session = future.getSession();
        if (session.isActive())
        {
            log.info("Connect to Comm {} is succeeds.", commName);
            session.setAttribute("KEY_SESSION_COMMNAME", commName);
            this.commSessionMap.put(commName, session);
        }

        log.info("Listener to comm: {}", commName);
    }

    public void scanComms()
    {
        try
        {
            List<String> tempCommList = new ArrayList();
            String scannerComm = properties.getScannerComm();
            String commName;
            if (null != scannerComm && !"".equals(scannerComm))
            {
                String[] comms = scannerComm.split(",");
                String[] var11 = comms;
                int var13 = comms.length;

                for (int var6 = 0; var6 < var13; ++var6)
                {
                    String comm = var11[var6];
                    tempCommList.add(comm);
                    if (!this.commList.contains(comm))
                    {
                        log.info("发现新设备，串口名为：{}", comm);
                        this.createIoSession(comm);
                        this.commList.add(comm);
                    }
                }
            } else
            {
                for (Enumeration comms = CommPortIdentifier.getPortIdentifiers(); comms.hasMoreElements();
                     tempCommList.add(commName))
                {
                    CommPortIdentifier commPort = (CommPortIdentifier) comms.nextElement();
                    commName = commPort.getName();
                    if (!this.commList.contains(commName))
                    {
                        log.info("发现新设备，串口名为：{}", commName);
                        this.createIoSession(commName);
                        this.commList.add(commName);
                    }
                }
            }

            if (tempCommList.size() < this.commList.size())
            {
                Iterator var10 = tempCommList.iterator();

                String comm;
                while (var10.hasNext())
                {
                    comm = (String) var10.next();
                    this.commList.remove(comm);
                }

                var10 = this.commList.iterator();

                while (var10.hasNext())
                {
                    comm = (String) var10.next();
                    log.info("设备已移除，串口名为：{}", comm);
                    IoSession session = (IoSession) this.commSessionMap.get(comm);
                    if (null != session)
                    {
                        session.closeOnFlush();
                        session.getCloseFuture().setClosed();
                    }
                }
            }
        } catch (InterruptedException var8)
        {
            log.error("Scanner comm has a error.{}", var8);
        }

    }

}
